package app.base.commons;

import java.sql.*;  

import javax.sql.*;  
import javax.naming.*;   
   
public class Db {
	InitialContext ctx;
	DataSource ds;
	Connection conn;
	Statement stmt;
	
	boolean autoCommit;
	
	private Db(String ctxLookUpName) throws Throwable {
		ctx = new InitialContext();
		
		ds=(DataSource)ctx.lookup(ctxLookUpName);
		
		conn = ds.getConnection();

		autoCommit = conn.getAutoCommit();

		stmt = conn.createStatement();
	}

	//synchronized
	public static Db getInstance(String ctxLookUpName) throws Throwable {
		return new Db(ctxLookUpName);
	}
	
	public void release() {
		try {
			this.conn.setAutoCommit(this.autoCommit);
			this.stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
  
	public Connection getConnection() {
		return this.conn;
	}
	
	public ResultSet executeQuery(String sql) throws SQLException {
		return this.stmt.executeQuery(sql);
	}
	
	public int executeUpdate(String sql) throws SQLException {
		return this.stmt.executeUpdate(sql);
	}
	
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		this.conn.setAutoCommit(autoCommit);
	}

	public void commit() throws SQLException {
		this.conn.commit();
	}
	
	public void rollback() throws SQLException {
		this.conn.rollback();
	}
}
